/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sakila.dao;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import sakila.util.HibernateUtil;

/**
 *
 * @author THANH LAM
 */
public abstract class AbstractDAO<T> {

    protected Session session = null;

    public AbstractDAO() {
        session = HibernateUtil.getSessionFactory().openSession();
    }

    public void create(T entity) {
        try {
            session.save(entity);
            System.out.printf("Insert sucess " + entity.toString());
         
        } catch (Exception e) {
            System.out.println("e=" + e.getMessage());
        } finally {
            session.flush();
            session.close();
        }

    }

    public void update(T entity) {
        try {
            session.update(entity);
            System.out.printf("Update sucess " + entity.toString());
            
        } catch (Exception e) {
            System.out.println("e=" + e.getMessage());
        } finally {
            session.flush();
            session.close();
        }
    }

    public abstract T searchById(int id);

    public void delete(T entity) {
        try {
            session.delete(entity);
            System.out.printf("Delete sucess " + entity.toString());
         
        } catch (Exception e) {
            System.out.println("e=" + e.getMessage());
        } finally {
            session.flush();
            session.close();
        }
    }

    public List executeHQLQuery(String hql) {
        try {


            session.beginTransaction();
            Query q = session.createQuery(hql);
            List resultList = q.list();
            //displayResult(resultList);

            session.getTransaction().commit();
            
            return resultList;
        } catch (HibernateException he) {
            he.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    public abstract List getAll();
}
